<?php
/**
 * Класс для цепочки валидаторов с возможностью задания условия OR.
 */
class Workset_Validate_List extends Zend_Validate {
	const MODE_OR = 1;
	const MODE_AND = 2;

	/**
	 * @var integer
	 */
	protected $_iMode = 0;

	/**
	 * Инициализация конструктора класса.
	 * 
	 * @param array $validators
	 * @param integer $mode
	 */
	public function __construct($validators, $mode = self::MODE_AND) {
		if (!is_array($validators)) {
			$validators = array('validators' => array($validators), 'mode' => $mode);
		}

		if (!array_key_exists('validators',$validators)) {
			$validators = array('validators' => $validators, 'mode' => $mode);
		}

		$validators['prefixPath'] = array(
				'validate' => array(
				'prefix' => 'Workset_Validate',
				'path' => 'Workset/Validate'
			),
		);

		$this->_iMode = isset($validators['mode']) && (strtoupper($validators['mode']) == 'OR' || $validators['mode'] == self::MODE_OR)
			? self::MODE_OR
			: self::MODE_AND;

		$oElement = new Zend_Form_Element('temp',$validators);
		foreach ($oElement->getValidators() as $mKey => $oValidator) {
			$this->addValidator($oValidator,true);
			$this->_validators[$mKey] = array_pop($this->_validators);
		}
	}

	/**
	 * Получение валидатора по его имени.
	 * 
	 * @param string $sName
	 * @return Zend_Validate_Interface
	 */
	public function getValidator($sName) {
		return isset($this->_validators[$sName])
			? $this->_validators[$sName]['instance']
			: null;
	}

	/**
	 * (non-PHPdoc)
	 * @see library/Zend/Zend_Validate#isValid()
	 */
	public function isValid($value) {
		if ($this->_iMode == self::MODE_AND) {
			return parent::isValid($value);
		}

		$this->_messages = array();
		$this->_errors   = array();
		$result = false;

		foreach ($this->_validators as $element) {
			$validator = $element['instance'];

			if ($validator->isValid($value)) {
				$this->_errors = array();
				$result = true;
				break;
			}

			$messages = $validator->getMessages();
			$this->_messages = array_merge($this->_messages, $messages);
			$this->_errors   = array_merge($this->_errors,   array_keys($messages));
		}

		return $result;
	}
}
?>